<!-- 弹窗 详情 -->
<script lang="tsx" setup>
import FileUpload from "@/components/file-system/file-upload.vue";
import type { FormDescChild } from "@/components/form-desc/form-desc.vue";
import { jeecgBootPlanSaveUsingPost, jeecgBootPlanUpdateUsingPut,jeecgBootPlanCoursesUsingGet} from "@/genapi/exam";
import { useAsync } from "@/hooks/use-async";
import FileOtherUpload from "@/components/file-system/file-otherUpload.vue";
import { ref } from "vue";
import {
	getEnumOptionsField,
	GATE_STATUS_OPTIONS,
	COURSE_TYPE_OPTIONS,
} from "@/config/enum-options";

import { injectState } from "../state";
import { useUserStore } from "@/stores/user";
// import ContentManage from './content-manage.vue'

const userStore = useUserStore();

defineOptions({ name: "DetailDialog" });

const img = import.meta.glob("./assets/*.png", {
	import: "default",
	eager: true,
});

const { page } = injectState()!;

const dialogRef = shallowRef<InstanceType<GlobalComponents["PromiseDialog"]>>();
const formDescRef = shallowRef<InstanceType<GlobalComponents["FormDesc"]>>();

const type = ref<"write" | "read" | "content" | "download" | "create">();

const beforeClose = async () => {
	if (type.value === "write") {
		await ElMessageBox.confirm("确认关闭？");
	}
};


const trigger = async (
	_type: "write" | "read" | "content" | "download" | "create",
	value = {} as any,
) => {
  // console.log('内容管理')
  // console.log(value)
	type.value = _type;
  // debugger;
  if(type.value === 'content'){
    tableData.value = value
    console.log(tableData.value)
  }
	model.value = JSON.parse(JSON.stringify(value)) as any;
  // console.log(model.value)

	await dialogRef.value?.open();
};

defineExpose({
	trigger,
});

const model = ref<(typeof page.records.value)[0]>({});
const value = ref("");

const file = computed({
	get() {
		if (model.value.fileId) {
			return [
				{
					id: model.value.fileId,
					name: model.value.fileName,
				},
			];
		}
	},
	set(value: any) {
		model.value.fileId = value?.[0]?.id;
	},
});

const title = computed(() => {
	if (type.value === "create") {
		return "新建课程";
	} else if (type.value === "content") {
		return "内容管理";
	} else {
		return `详情`;
	}
});

const { execute, isLoading } = useAsync(async () => {
	await formDescRef.value?.formRef?.validate();
	await ElMessageBox.confirm("确认提交？", "提示", {
		type: "warning",
	});
	if (type.value === "create") {
		await jeecgBootPlanSaveUsingPost({
			data: {
				...model.value,
			},
		});
	} else if (type.value === "content") {
		await jeecgBootPlanCoursesUsingGet({
			params:{
          planId : model.value.id
        }
		});
	}else if (type.value === "write") {
		await jeecgBootPlanUpdateUsingPut({
			data: {
				...model.value,
			},
		});
	}

	ElMessage.success("提交成功");
	page.execute();
	dialogRef.value?.complete();
});
const selectOptions = ref([{ label: "员工", value: "1" }]);

function getCurrentDate(): string {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, "0");
	const day = String(now.getDate()).padStart(2, "0");

	return `${year}-${month}-${day}`;
}
model.value.time = getCurrentDate();

const inputValue = ref("");
const dynamicTags = ref(["Tag 1", "Tag 2", "Tag 3"]);
const inputVisible = ref(false);
const InputRef = ref();

const handleClose = (tag: string) => {
	model.value.tag.splice(model.value.tag.indexOf(tag), 1);
};

const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value!.input!.focus();
	});
};

const handleInputConfirm = () => {
	if (!model.value.tag) {
		model.value.tag = [];
	}
	if (inputValue.value) {
		model.value.tag.push(inputValue.value);
	}
	inputVisible.value = false;
	inputValue.value = "";
};

const tableData = ref([]);

let i = ref(0)
const addTableRow = () => {
  if(i.value>0){
    ElMessage.error('请先将当前新增内容完善完成')
    return
  }
	tableData.value.push({
		courseName: "",
		coverList: [],
		credit: 0,
		contentType: "",
		progress: 0,
		fileName: "",
	});
  i.value += 1
};

//内容管理的确认按钮提交
const contentManageSubmit = (data) => {
  console.log(111)
  console.log(data)

}

const isshowName = ref(false)
//控制课程名称输入框的显示
const showName = (name) => {
  // console.log(name)
  if(isshowName.value === true){
    return true
  }else{
    if(name){
    isshowName.value = true
    }
    else{
     return false
    }
    }
}

const isshowCredits = ref(false)
//控制课程学分输入框的显示
const showCredits = (name) => {
  // console.log(name)
  if(isshowCredits.value === true){
    return true
  }else{
    if(name){
    isshowCredits.value = true
    }
    else{
     return false
    }
    }
}

//新增内容管理的请求参数
let addContentManage = ref(
  {
      "content": "",
      "cover": "",
      "credits": 0,
      "duration": 0,
      "id": "",
      "name": "",
      "type": ""
    }
)

//上传文件封面成功的函数
const coverFileUpload = (res) => {
  // console.log(res.result)
}
//上传文件函数
const httpRequest = async (options: UploadRequestOptions): Promise<any> => {
  console.log(options.file)
	const file = options.file as unknown as File & { uid?: string };
	const type = userStore.imgType;
	try {
    const formData: any = new FormData();
    formData.append("file", options.file);
    const { authorization } = useUserStore();
    const option= {
            headers: {
                    "X-Access-Token": authorization,
            },
    };
    const {data} =await axios.post('/jeecg-boot/dev/file/uploadLocalReturnUrl',formData,option);
    console.log(data)
		options.onSuccess(data);
		return data;
	} catch (error: any) {
    console.log(error)
		return options.onError(error);
	}
}
//删除文件
const deleteFile = async(id) => {
  const { authorization } = useUserStore();
    const option= {
            headers: {
                    "X-Access-Token": authorization,
            },
    };
    const data =await axios.post('/jeecg-boot/dev/file/delete',[{id:id}],option);
    console.log(data)
    ElMessage.success(data.data.message)

}
//删除封面文件
const deleteCoverFile = (data) => {
  if(!data.coverFile){
    console.log('封面不存在')
    return
  }
  console.log(data.coverFile.id)
  deleteFile(data.coverFile.id)
}
//删除内容文件
const deleteContentFile = (data) => {
  console.log(data.contentFile)
  if(!data.contentFile){
    console.log('内容不存在')
    return
  }
  console.log(data.contentFile.id)
  deleteFile(data.contentFile.id)
}
const children: FormDescChild[] = [
	{
		label: "培训类型",
		prop: "type",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-select-v2
				v-model={model.value.type}
				options={COURSE_TYPE_OPTIONS}
				clearable
				placeholder="请选择类型"
			/>
		),
		descItem: () =>
			getEnumOptionsField(COURSE_TYPE_OPTIONS, "label", model.value.type) ??
			"-",
	},
	{
		label: "课程名称",
		prop: "name",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.name} placeholder="请输入" />
		),
		descItem: () => `${model.value.name ?? "-"}`,
	},
	{
		label: "标签",
		prop: "tag",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
			<div
				style="
				width: 100%;
				align-items: center;
				border: 1px solid #dcdfe6;
				padding: 2px;
			"
			>
				{model.value.tag?.map((item) => (
					<el-tag
						style="margin-right:5px;"
						key={item}
						closable
						onClose={() => handleClose(item)}
					>
						{item}
					</el-tag>
				))}
				{inputVisible.value ? (
					<el-input
						ref="InputRef"
						v-model={inputValue.value}
						style="width:80px"
						size="small"
						onKeyup={{
							enter: handleInputConfirm,
						}}
						onBlur={handleInputConfirm}
					/>
				) : (
					<el-button class="button-new-tag" size="small" onClick={showInput}>
						+ New Tag
					</el-button>
				)}
			</div>
		),
		descItem: () => `${model.value.tag ?? "-"}`,
	},
	{
		label: "学分",
		prop: "credits",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<el-input v-model={model.value.credits} placeholder="请输入" />
		),
		descItem: () => `${model.value.credits ?? "-"}`,
	},
	{
		label: "课节数",
		prop: "courseNum",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => <el-input v-model={model.value.courseNum} placeholder="请输入" />,
		descItem: () => `${model.value.courseNum ?? "-"}`,
	},
	{
		label: "课程简介",
		prop: "description",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
			<el-input
				v-model={model.value.description}
				type="textarea"
				placeholder="请输入课程简介"
				rows={4}
			/>
		),
		descItem: () => `${model.value.description ?? "-"}`,
	},
	{
		label: "课程图片",
		prop: "img",
		rule: [{ required: false, message: "请输入", trigger: "blur" }],
		span: 1,
		formItem: () => (
			<div style={{ marginTop: "10px", marginLeft: "15px" }}>
				<FileOtherUpload
					onClick={() => {
						userStore.imgType = "课程图片";
					}}
				/>
				<div
					style={{
						whiteSpace: "normal",
						width: "150px",
						color: "rgba(0, 0, 0, 0.25)",
					}}
				>
					支持bmp,jpg,png,tif格式图片，可添加多个图片
				</div>
			</div>
		),
		descItem: () => `${model.value.img ?? "-"}`,
	},
  //内容管理表格
	{
		label: "",
		// prop: "content",
		fontSize: "16px",
		fontWeight: 700,

		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => <div style='color: #1D2129;'>道路危险货运基础知识篇</div>,
	},
	{
		label: "",
		// prop: "applyDate",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => {
			const handlePictureCardPreview = () => {};

			const handleRemove = () => {};
			return (
        <div style="width:100%">
				<el-table data={tableData.value} style="width: 100%;">
					{/* <el-table-column type="index" label="排序" width="60" /> */}
          <el-table-column type="index" label="排序" width="60" >
          </el-table-column>

					{/* <el-table-column prop="name" label="课程名称" /> */}
          <el-table-column prop="name" label="课程名称">
            {{
              default: (scope) => (
                <div>
                <input
                 v-model={scope.row.name} 
                 placeholder="请输入内容" 
                 style="width: 161.5px;height: 32px;background: #F7F8FA; text-align: center;" 
                 v-show={showName(scope.row.name)}
                 ></input>
                 <input
                 v-model={addContentManage.value.name} 
                 v-show={!showName(scope.row.name)}
                 class='nameContent'
                 style="width: 161.5px;height: 32px;background: #F7F8FA; text-align: center;" 
                 ></input>
                </div>
              )
            }}
          </el-table-column>

					<el-table-column label="课程封面">
						{/* <el-icon class="i-custom:delete" color="red" /> */}
						{{
            default: (scope) => (
              <div>
                <el-link type="primary" underline={false} v-show={scope.row.coverFile}>{scope.row.coverFile? scope.row.coverFile.name:'上传'}</el-link>
                <el-icon class="i-custom:delete" 
                color="red" v-show={scope.row.coverFile} 
                style="margin-left: 13px; margin-top: 5px; cursor: pointer;"
                onClick={() => deleteCoverFile(scope.row)}
                />
                <el-upload
                  class="upload-demo"
                  http-request={httpRequest}
                  on-success={coverFileUpload}
                  multiple
                  style="color: #165DFF; padding-top: 10px;"
                  v-show={!scope.row.coverFile}
                  limit={3}>上传</el-upload>
              </div>
              
            )
          }}
					</el-table-column>

					{/* <el-table-column prop="credits" label="学分" width="60" /> */}
          <el-table-column prop="credits" label="学分" width="60" >
            {{
              default: (scope) => (
                <div>
                  <div>
                <input
                 v-model={scope.row.credits} 
                 placeholder="请输入内容" 
                 style="width: 44px;height: 32px;background: #F7F8FA; text-align: center;" 
                 v-show={showCredits(scope.row.name)}
                 ></input>
                 <input
                 v-model={addContentManage.value.credits} 
                 v-show={!showCredits(scope.row.name)}
                 class='nameContent'
                 style="width: 44px;height: 32px;background: #F7F8FA; text-align: center;" 
                 ></input>
                </div>
                </div>
              )
            }}

          </el-table-column>

					<el-table-column prop="type" label="内容类型" width="120">
						{{
							default: (scope) => (
								<select
									v-model={scope.row.type}
									placeholder="请选择"
                  style='width: 86px;
                        height: 32px;
                        background: #F7F8FA;'
								>
									<option label="PDF" value="1" />
									<option label="视频" value="2" />
									<option label="PPT" value="0" />
								</select>
							),
						}}
					</el-table-column>

					<el-table-column label="内容">
						{{
							default: (scope) => (
								<div>
									{scope.row.type === "1" && (
                    //1是pdf
                    <div>
                      <el-link type="primary" underline={false} v-show={scope.row.typeText === 'PDF' && scope.row.contentFile? true:false}>{scope.row.contentFile? scope.row.contentFile.name:'空PDF.pdf'}</el-link>
                        <el-icon class="i-custom:delete" color="red" 
                        v-show={scope.row.typeText === 'PDF' && scope.row.contentFile? true:false} 
                        onClick={() => deleteContentFile(scope.row)}
                        style="margin-left: 13px; margin-top: 5px; cursor: pointer;"
                        />
                      <el-upload
                        class="upload-demo"
                        http-request="httpRequest"
                        multiple
                        style="color: #165DFF; padding-top: 10px;"
                        v-show={scope.row.typeText === 'PDF' && scope.row.contentFile? false:true}
                        limit={3}>上传PDF</el-upload>
                    </div>
									)}
									{scope.row.type === "0" && (
                    //0是ppt
										<div>
                      <el-link type="primary" underline={false} v-show={scope.row.typeText === 'PPT'? true:false}>{scope.row.contentFile && scope.row.contentFile? scope.row.contentFile.name:'空PPT'}</el-link>
                        <el-icon class="i-custom:delete" color="red" 
                        v-show={scope.row.typeText === 'PPT' && scope.row.contentFile? true:false} 
                        onClick={() => deleteFile(scope.row)}
                        style="margin-left: 13px; margin-top: 5px; cursor: pointer;"
                        />
                      <el-upload
                        class="upload-demo"
                        http-request="httpRequest"
                        multiple
                        style="color: #165DFF; padding-top: 10px;"
                        v-show={scope.row.typeText === 'PPT'? false:true}
                        limit={3}>上传PPT</el-upload>
                    </div>
									)}
									{scope.row.type === "2" && (
                    //2是视频
                    <div>
                      <el-link type="primary" underline={false} v-show={scope.row.typeText === '音视频' && scope.row.contentFile? true:false}>{scope.row.contentFile? scope.row.contentFile.name:'空音视频'}</el-link>
                        <el-icon class="i-custom:delete" color="red" 
                        v-show={scope.row.typeText === '音视频' && scope.row.contentFile? true:false} 
                        onClick={() => deleteContentFile(scope.row)}
                        style="margin-left: 13px; margin-top: 5px; cursor: pointer;"
                        />
                      <el-upload
                        class="upload-demo"
                        http-request="httpRequest"
                        multiple
                        style="color: #165DFF; padding-top: 10px;"
                        v-show={scope.row.typeText === '音视频' && scope.row.contentFile? false:true}
                        limit={3}>上传音视频</el-upload>
                    </div>
									)}
									{scope.row.progress === 100 && (
										<el-icon class="i-custom:delete" color="red" />
									)}
								</div>
							),
						}}
					</el-table-column>
				</el-table>
        <div style="border: 1px solid #D9D9D9; border-top: 0px;">
          <el-button
            type="primary"
            style='margin: 5px 0px 5px 705px;'
            onClick={() => {
              addTableRow();
            }}
          >
            +增加
        </el-button>
      </div>
    </div>
			);
		},
	},
	{
		label: "",
		// prop: "content",
		rule: [{ required: true, message: "请输入", trigger: "blur" }],
		span: 2,
		formItem: () => (
      <div style='display: flex; margin-left: 650px'>
        <el-button
          type="info"
          onClick={() => {
            dialogRef?.value.close()
          }}
        >
          取消
        </el-button>
        <el-button
          type="primary"
          
          onClick={() => {
            contentManageSubmit(tableData.value)
          }}
        >
          确认
        </el-button>
      </div>

		),
	},
];

interface Option {
	key: number;
	label: string;
	initial: string;
}

const generateData = () => {
	const data: Option[] = [];
	const states = [
		"California",
		"Illinois",
		"Maryland",
		"Texas",
		"Florida",
		"Colorado",
		"Connecticut ",
	];
	const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
	states.forEach((city, index) => {
		data.push({
			label: city,
			key: index,
			initial: initials[index],
		});
	});
	return data;
};

const data = ref<Option[]>(generateData());
const value1 = ref([]);

const filterMethod = (query, item) => {
	return item.initial.toLowerCase().includes(query.toLowerCase());
};

const getChildren = () => {
	let updatedChildren = [...children];
	if (type.value === "create" || type.value === "write") {
		return updatedChildren.slice(0, updatedChildren.length - 3);
	} else if (type.value === "content") {
		return updatedChildren.slice(
			updatedChildren.length - 3,
			updatedChildren.length,
		);
	}
};
</script>

<template>
	<PromiseDialog
		ref="dialogRef"
		:title="title"
		:w="'900px!'"
		:before-close="beforeClose"
	>
		<el-scrollbar style="height: 508px">
			<!-- <ContentManage v-if="type === 'write'" :courses="list" /> -->
			<FormDesc
				ref="formDescRef"
				m="t-24px x-30px"
				:type="type === 'read' ? 'desc' : 'form'"
				form-class="gap-x-20px"
				:model="model"
				:children="getChildren()"
				:column="2"
			/>
		</el-scrollbar>
		<template v-if="type === 'create' || type === 'write'" #footer>
			<el-button @click="dialogRef?.close()">取消</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>确定</el-button
			>
		</template>
		<template v-else-if="type === 'create'" #footer>
			<el-button @click="dialogRef?.close()">拒绝</el-button>
			<el-button type="primary" :is-loading="isLoading" @click="execute()"
				>通过</el-button
			>
		</template>
	</PromiseDialog>
</template>

<style lang="scss" scoped>
.trainingListBox {
	width: 100%;
	padding: 0px 30px;

	.listBoxTitle {
		height: 50px;
		width: 100%;
		display: flex;
		align-items: center;
	}
}
</style>
